import React, { useEffect, useMemo, useRef, useState } from 'react';
import { List, message, Skeleton } from 'antd';
import MessageItem from './MessageItem';
import { SvgIcon } from '@/components/icon';
import { ChatItem } from '@/types/chat';
import { useThrottleFn, useUpdateLayoutEffect } from 'ahooks';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useChatRecordLoading } from '@/store/configStore';
import AvatarDisplay from '@/components/work-modal/components/AvatarDisplay';
import { AppType } from '@/common/app/constants';
import DigitalHuman from '@/components/digital-human';
import { useParams } from '@/router/hooks';
import { useMetahumanStore } from '@/store/metahumanStore';
import { useOrchestrationStore } from '@/store/orchestrationStore';


interface ChatListProps {
  messages: ChatItem[];
  isMessageSend?: boolean;
  deleteMessage?: (index: number) => void;
  reFreshAnswer?: (index: number) => void;
  handleSend?: (message: string) => void;
  isChat?: boolean;
  guessQuestions?: { id: string; content: string }[];
  onQuestionClick?: (question: string) => void;
  workflowDebug?: boolean;
}

const ChatList = ({
  messages,
  isMessageSend,
  deleteMessage,
  handleSend,
  reFreshAnswer,
  isChat = true,
  guessQuestions,
  onQuestionClick,
  workflowDebug = false,
}: ChatListProps) => {
  const chatListRef = useRef<HTMLDivElement>(null);
  const chatListWrapperRef = useRef<HTMLDivElement>(null);
  const [hideItem, setHideItem] = useState(false);
  const [isUserScrolling, setIsUserScrolling] = useState(false);
  const { isPc } = useWindowWidth();
  const chatRecordLoading = useChatRecordLoading();
  const [thinkState, setThinkState] = useState<1 | 2>(1);
  // const [starState, setStarState] = useState<1 | 2 | 3 | 4>(1);
  const { appId = '' } = useParams() as { appId: string };

  const {
    appLogo: appLogoStore,
    appName: appNameStore,
    isInOrchestrationPage,
  } = useOrchestrationStore();


  const {
    virtualAvatarEnabled,
    permissionConfig
  } = useMetahumanStore();

  useEffect(() => {
    const timer = setInterval(() => {
      setThinkState((prev) => (prev === 1 ? 2 : 1));
      // setStarState((prev) => (prev === 3 ? 1 : (prev + 1) as typeof prev));
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  const { run } = useThrottleFn(
    () => {
      if (isPc) {
        if (!isUserScrolling && chatListRef.current) {
          chatListRef.current.scrollTop = chatListRef.current.scrollHeight;
        }
      } else {
        if (!isUserScrolling && chatListWrapperRef.current) {
          chatListWrapperRef.current.scrollTop = chatListWrapperRef.current.scrollHeight;
        }
      }
    },
    { wait: 500 },
  );

  // 监听滚动事件
  useEffect(() => {
    const handleScroll = () => {
      console.log('handleScroll')
      const ref = isPc ? chatListRef : chatListWrapperRef;
      if (ref.current) {
        const currentScrollTop = ref.current.scrollTop;
        const previousScrollTop = ref.current.getAttribute('data-previous-scroll-top');
        // message.info(Number(previousScrollTop)?.toString() + '-' + (currentScrollTop + 50)?.toString() + '-' + (currentScrollTop + chatListRef.current.clientHeight)?.toString() + '-' +  ((chatListRef.current.scrollHeight || 0) - 150)?.toString())
        // console.log(previousScrollTop, currentScrollTop, currentScrollTop + ref.current.clientHeight, ref.current.scrollHeight - 150)

        if (previousScrollTop && currentScrollTop > 50 && Number(previousScrollTop) > (currentScrollTop + 50)) {
          setIsUserScrolling(true);
        } else {
          const atBottom =
            currentScrollTop + ref.current.clientHeight >=
            ref.current.scrollHeight - 150;
          setIsUserScrolling(!atBottom);
        }

        ref.current.setAttribute('data-previous-scroll-top', currentScrollTop.toString());
      }
    };

    const chatListElement = chatListRef.current;

    if (chatListElement) {
      chatListElement.addEventListener('scroll', handleScroll);
    }

    return () => {
      if (chatListElement) {
        chatListElement.removeEventListener('scroll', handleScroll);
        chatListElement.setAttribute('data-previous-scroll-top', '0');
      }
    };
  }, []);

  useEffect(() => {
    console.log('触发几次', isMessageSend);

    if (isMessageSend == true) {
      setIsUserScrolling(false);
    }
    // run();
    setHideItem(isMessageSend ?? false);
  }, [isMessageSend]);
  const chatList = document.querySelector('.chat-list');


  useUpdateLayoutEffect(() => {
    if (!isUserScrolling) {
      run();
    }
  }, [messages]);

  // 最后一个消息大小变化后触发滚动到最后
  const scrollToBottom = () => {
    run();
  };

  const isWebRTCSopport = useMemo(() => {
    return typeof window !== 'undefined' && typeof window.RTCPeerConnection !== 'undefined';
  }, []);

  const isMetahumanEnabled = useMemo(() => {
    return virtualAvatarEnabled && permissionConfig?.metahumanQuota && isWebRTCSopport;
  }, [virtualAvatarEnabled, permissionConfig, isWebRTCSopport]);

  const messageInput = document.querySelector('.qa-message-send-input');
  const messageInputHeight = useMemo(() => {
    if (!isPc) {
      if (chatList?.clientHeight && window.innerHeight - chatList?.clientHeight < 50) {
        return (messageInput?.clientHeight ?? 0) + 120;
      }
      return (messageInput?.clientHeight ?? 0) + 20;
    }
    return undefined;
  }, [messageInput?.clientHeight, isPc, chatList?.clientHeight]);

  return (
    <div 
      ref={chatListWrapperRef}
      className={`chat-list hide-scrollbar flex-1 overflow-y-auto px-2 ${isPc ? 'flex justify-center pt-4 w-[800px]' : 'mt-[200px] relative'}`}
      style={{ 
        paddingBottom: messageInputHeight,
      }}>
        {/* DigitalHuman 固定区域 - 非PC端 */}
        {!isPc && isMetahumanEnabled && (
          <div className="fixed top-0 left-0 right-0 z-50 bg-white flex justify-center">
            <div className="relative">
              <DigitalHuman/>
              {/* 渐变遮罩层，底部渐变到白色 */}
              <div className="absolute left-0 bottom-0 w-full h-1/2 pointer-events-none" style={{
                background: 'linear-gradient(to bottom, rgba(255,255,255,0) 0%, #fff 30%)'
              }} />
            </div>
          </div>
        )}
        
        {/* 左侧消息列表区域 */}
        <div
          ref={chatListRef}
          className={`chat-list hide-scrollbar flex-1 overflow-y-auto px-2 ${isPc ? 'w-[500px]' : 'w-full absolute z-[300]'}`}
          style={{ 
            paddingBottom: messageInputHeight,
          }}
        >
          {messages.length > 0 && (
            <List
              className="w-full"
              itemLayout="horizontal"
              split={false}
              dataSource={messages}
              renderItem={(item, index) => (
                <List.Item>
                  <div
                    className={`flex w-full flex-col ${item.isUser ? 'justify-end' : 'justify-start'}`}
                  >
                    {!item.isUser && (
                      <div className="flex items-center">
                        {item?.appLogo && (
                          <>
                            <AvatarDisplay
                              src={isInOrchestrationPage && appId == item?.appId ? appLogoStore : item?.appLogo as string}
                              size={24}
                              className="h-[24px] w-[24px] flex-shrink-0"
                            />
                            <div className="flex-shrink-0 pl-2 text-[14px] font-font-weight-600 text-text-5">
                              {isInOrchestrationPage && appId == item?.appId ? appNameStore : item?.appName}
                            </div>
                          </>
                        )}
                        <div className="ml-2 font-bold" style={{ height: '14px', display: 'flex', alignItems: 'center' }}>
                          {item.loading && (
                            <div className="flex items-center" style={{ overflow: 'visible' }}>
                              {/* 思考icon */}
                              <div
                                style={{
                                  width: '50px',
                                  height: '50px',
                                  marginRight: '8px',
                                  overflow: 'visible',
                                  display: 'flex',
                                  alignItems: 'center',
                                  justifyContent: 'center',
                                  position: 'relative',
                                }}
                              >
                                {[1, 2].map((state) => (
                                  <SvgIcon
                                    key={state}
                                    icon={`ai-chat-think${state}`}
                                    color="var(--brand-color)"
                                    style={{
                                      width: '50px',
                                      height: '50px',
                                      position: 'absolute',
                                      opacity: thinkState === state ? 1 : 0,
                                      transition: 'opacity 500ms linear 1ms',
                                    }}
                                  />
                                ))}
                              </div>
                              {/* 星星旋转图标 */}
                              <div className="flex justify-center items-center" style={{ width: '14px', height: '14px', position: 'relative' }}>
                                <SvgIcon
                                  icon="ai-chat-star1"
                                  color="var(--brand-color)"
                                  size="14"
                                  style={{
                                    animation: 'star-spin 1.2s linear infinite',
                                    width: '14px',
                                    height: '14px',
                                  }}
                                />
                              </div>
                            </div>
                          )}
                        </div>
                      </div>
                    )}
                    <MessageItem
                      key={index}
                      item={item}
                      index={index}
                      isMessageSend={isMessageSend}
                      hideItem={hideItem}
                      handleSend={handleSend ?? (() => {})}
                      isLastOne={index === messages.length - 1}
                      scrollToBottom={scrollToBottom}
                      deleteMessage={deleteMessage}
                      reFreshAnswer={reFreshAnswer}
                      guessQuestions={guessQuestions}
                      onQuestionClick={onQuestionClick}
                      workflowDebug={workflowDebug}
                    ></MessageItem>
                  </div>
                </List.Item>
              )}
            />
          )}
        </div>
        
        {/* 右侧固定区域 */}
        {isPc && isMetahumanEnabled && (
          <div className="w-[300px] h-[400px]flex-shrink-0 px-4 flex items-end">
            <div className="text-sm text-gray-600">
              <DigitalHuman/>
            </div>
          </div>
        )}
    </div>
  );
};

export default React.memo(ChatList);
